package com.Jian.reggie.controller;

import com.Jian.reggie.common.BaseContext;
import com.Jian.reggie.common.R;
import com.Jian.reggie.dto.OrdersDto;
import com.Jian.reggie.dto.SetmealDto;
import com.Jian.reggie.impl.Category;
import com.Jian.reggie.impl.OrderDetail;
import com.Jian.reggie.impl.Orders;
import com.Jian.reggie.impl.Setmeal;
import com.Jian.reggie.service.OrderDetailService;
import com.Jian.reggie.service.OrdersService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: OrderController
 * Package: com.Jian.reggie.controller
 * Description:
 *
 * @Author 蹇泽阳
 * @Create 2023/11/29 15:09
 * @Version 1.0
 */
@RequestMapping("/order")
@Slf4j
@RestController
public class OrderController {
  @Autowired
  private OrdersService orderService;
  @Autowired
  private OrderDetailService orderDetailService;
  
  @PostMapping("/submit")
  public R submitOrder(@RequestBody Orders orders) {
    log.info("orders: {}", orders);
    orderService.submitOrder(orders);
    
    return R.success("提交成功");
  }
  
  
  // 订单详情页分页
  @GetMapping("/userPage")
  public R<Page<OrdersDto>> getUserPage(@RequestParam Integer page, @RequestParam Integer pageSize) {
    Long userid = BaseContext.getCurrentId();
    // 将orders表对应的数据查出来
    Page<Orders> ordersPage = new Page<>(page, pageSize);
    LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(Orders::getUserId, userid);
    orderService.page(ordersPage, queryWrapper);
    
    // 将setmeal表对应的数据转换成setmealDto
    Page<OrdersDto> ordersDtoPage = new Page<>(page, pageSize);
    BeanUtils.copyProperties(ordersPage, ordersDtoPage, "records");
    
    
    // 查找出对应的分类名称,放到setmealDto中
    List<OrdersDto> setmealDtos = ordersPage.getRecords().stream().map((order -> {
      LambdaQueryWrapper<OrderDetail> orderDetailWrapper = new LambdaQueryWrapper<>();
      OrdersDto ordersDto = new OrdersDto();
      BeanUtils.copyProperties(order, ordersDto);
      orderDetailWrapper.eq(OrderDetail::getOrderId, order.getId());
      ordersDto.setOrderDetails(orderDetailService.list(orderDetailWrapper));
      return ordersDto;
    })).collect(Collectors.toList());
    
    ordersDtoPage.setRecords(setmealDtos);
    return R.success(ordersDtoPage);
  }
  
  
  @PutMapping
  public R updateOrder(@RequestBody Orders orders) {
    LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
    LambdaQueryWrapper<Orders> one = wrapper.eq(Orders::getId, orders.getId());
    Orders oneOrder = orderService.getOne(one);
    oneOrder.setStatus(orders.getStatus());
    
    orderService.updateById(oneOrder);
    return R.success("更新成功");
  }
  
}
